# -*- coding: utf-8 -*-
"""
@ Created on 2024-06-14 12:23
---------
@summary: 字典类型API实现
---------
@author: Lsaiah
"""

from fastapi import APIRouter, Depends, Query
from typing import Optional
from core.auth import AuthHandler
from component.abstractCrud import AbstractCRUD
from core.response import ResponseModel, ListResponseModel
from constant import *
from ..models.form.dict_type_form import DictTypeCreateRequest, DictTypeUpdateRequest
from ..models.curd.dict_type_crud import DictType, DictTypeCRUD
from ..models.curd.dict_item_crud import DictItem, DictItemCRUD

dict_type_router = APIRouter(prefix="/system/dict/type", tags=["系统字典类型管理"])
auth_handler = AuthHandler()


class DictTypeCRUDAPI(AbstractCRUD[DictType, DictTypeCreateRequest, DictTypeUpdateRequest]):
    """字典类型CRUD API实现类"""
    
    def __init__(self):
        super().__init__(
            model=DictType,
            crud_class=DictTypeCRUD,
            create_schema=DictTypeCreateRequest,
            update_schema=DictTypeUpdateRequest
        )
    
    def get_router(self):
        """获取路由"""
        return dict_type_router


# 创建实例
dict_type_crud_api = DictTypeCRUDAPI()

# 注册路由
@dict_type_router.get("/page", response_model=ListResponseModel)
async def get_dict_types(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """获取字典类型列表"""
    return await dict_type_crud_api.page(page=page, size=size, search=search, is_active=is_active,is_deleted=0)


@dict_type_router.get("/get", response_model=ResponseModel)
async def get_dict_type(
    id: int = Query(..., description="字典类型ID"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """获取字典类型详情"""
    return await dict_type_crud_api.get(id=id)


@dict_type_router.post("/create", response_model=ResponseModel)
async def create_dict_type(
    dict_type_data: DictTypeCreateRequest,
    current_user = Depends(auth_handler.get_current_active_user())
):
    """创建字典类型"""
    return await dict_type_crud_api.create(data=dict_type_data)


@dict_type_router.put("/update", response_model=ResponseModel)
async def update_dict_type(
    dict_type_data: DictTypeUpdateRequest,
    current_user = Depends(auth_handler.get_current_active_user())
):
    """更新字典类型"""
    return await dict_type_crud_api.update(data=dict_type_data)


@dict_type_router.delete("/delete", response_model=ResponseModel)
async def delete_dict_type(
    id: int = Query(..., description="字典类型ID"),
    current_user = Depends(auth_handler.get_current_active_user())
):
    """删除字典类型"""
    try:
        # 检查是否有字典项
        dict_items = await DictItemCRUD.get_list(dict_type_id=id)
        if dict_items:
            return ResponseModel.error(
                code=CODE_ERROR,
                message="字典类型下有字典项，不能删除",
                data=None
            )
        
        # 检查是否为系统字典类型
        dict_type = await DictTypeCRUD.get_by_id(id)
        print(dict_type) #DictType(id=1, name=是否启用)
        if dict_type and dict_type.is_system:
            return ResponseModel.error(
                code=CODE_ERROR,
                message="系统字典类型不能删除",
                data=None
            )
        
        return await dict_type_crud_api.delete(id=id)
        
    except Exception as e:
        from log import logger
        logger.error(f"删除字典类型失败: {str(e)}")
        return ResponseModel.error(
            code=CODE_ERROR,
            message="删除字典类型失败",
            data=None
        )






